package com.epidemy

import java.io.{FileInputStream, File}
import java.security.Permission
import java.net.{SocketPermission, URL}

object ProgramRunner {
  def main(args: Array[String]) = {
    val Array(privileged, codeFile, classServerURLString) = args
    val code = {
      val f = new File(codeFile)
      val l = f.length.toInt
      val b = new Array[Byte](l)
      val in = new FileInputStream(f)
      in.read(b)
      in.close
      b
    }
    try {
      val classServerURL = new URL(classServerURLString)
      val preparedDeserialization = Grid.Program(code, classServerURL).prepareDeserialization
      privileged match {
        case "true" =>
        case "false" =>
          val allowedAddress = classServerURL.getHost + ":" + classServerURL.getPort
          System.setSecurityManager(new SecurityManager {
            override def checkPermission(permission: Permission): Unit = {
              //println("Checking permission ")
              if (permission.isInstanceOf[SocketPermission]) {
                val sp = permission.asInstanceOf[SocketPermission]
                if (sp.getActions == "connect" && allowedAddress == sp.getName) {
                  println("Allowed connection to class server")
                  return;
                }
              }
              super.checkPermission(permission)
            }
          })
      }
      preparedDeserialization()()
    } catch {
      case ex =>
        ex.printStackTrace(System.out)
        ex.printStackTrace(System.out)
    }
  }
}